/*
 * @Author: DUST
 * @Date: 2023-06-13 09:18:30
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-17 16:51:48
 * @FilePath: \koa-node-ts\utils\request.ts
 * @Description: 
 * undefined
 */
'use strict'

import request from "request";

/** url参数转换 */
const obj2String = (obj: any, arr: any[] = [], idx = 0) => {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]]
  }
  return new URLSearchParams(arr).toString()
}

/** 第三方接口 调用 */
const requestApi = <T>(method = 'get', url: string, params: any = null): Promise<T> => {
  return new Promise((resolve, reject) => {
    if (method === 'get') {
      if (params) {
        url += '?' + obj2String(params)
      }
      request.get(url, function (error: any, response: any, body: string) {
        if (!error && response.statusCode == 200) {
          resolve(JSON.parse(body) as T)
        } else {
          reject(error)
        }
      })
    } else {
      const option = {
        url: url,
        method: 'post',
        json: true,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'content-type': 'application/json'
        },
        body: params
      }
      request(option, function (error: any, response: any, body: T) {
        if (!error && response.statusCode == 200) {
          resolve(body)
        } else {
          reject(error)
        }
      })
    }
  })
}
export default requestApi;
